package com.aspire.boc.mms.wmf.servlets;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidCode extends HttpServlet {
	private static final long serialVersionUID = 6381512171234850807L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.reset();

		response.setContentType("image/png");

		BufferedImage image = new BufferedImage(70, 20, 1);

		Graphics g = image.getGraphics();

		g.setColor(getRandColor(230, 250));

		g.fillRect(0, 0, 70, 20);

		Random r = new Random();
		for (int i = 0; i < 133; i++) {
			g.setColor(getRandColor(150, 210));
			int x1 = r.nextInt(70);
			int y1 = r.nextInt(20);
			int x2 = r.nextInt(12);
			int y2 = r.nextInt(12);
			g.drawLine(x1, y1, x2 + x1, y2 + y1);
		}

		String regCode = "";
		g.setFont(new Font("Times New Roman", 1, 18));

		for (int i = 0; i < 5; i++) {
			g.setColor(getRandColor(50, 150));
			int num = getCode();

			if (num > 10) {
				char temp = (char) num;
				regCode = regCode + temp;
				g.drawString(String.valueOf(temp), 13 * i + 6, 16);
			} else {
				regCode = regCode + num;
				g.drawString(String.valueOf(num), 13 * i + 6, 16);
			}
		}

		System.out.println("\n" + regCode);
		request.getSession().setAttribute("validcode", regCode);

		ServletOutputStream sos = response.getOutputStream();
		ImageIO.write(image, "PNG", sos);
		sos.flush();
		sos.close();
	}

	private Color getRandColor(int low, int high) {
		Random ran = new Random();
		int r = low + ran.nextInt(high - low);
		int g = low + ran.nextInt(high - low);
		int b = low + ran.nextInt(high - low);

		return new Color(r, g, b);
	}

	private int getCode() {
		Random r = new Random();
		int code = 0;

		int flag = r.nextInt(3);
		if (flag == 0)
			code = r.nextInt(10);
		else if (flag == 1)
			code = getCodeByScope(97, 122);
		else {
			code = getCodeByScope(65, 90);
		}
		return code;
	}

	private int getCodeByScope(int low, int high) {
		Random ran = new Random();
		return low + ran.nextInt(high - low);
	}
}
